package cn.gson.school.controller.zhaosheng;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.school.dao.caiwu.ShouKuanDao;
import cn.gson.school.dao.caiwu.ShouKuanInfoDao;
import cn.gson.school.dao.jiaoxue.ClassDao;
import cn.gson.school.dao.jiaoxue.StudentDao;
import cn.gson.school.dao.qiantai.TeamStudentDao;
import cn.gson.school.dao.xitong.DeptSerchDao;
import cn.gson.school.dao.xitong.RoleSerchDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.dao.zhaosheng.InputStudentDao;
import cn.gson.school.dao.zhaosheng.SigninggrecordDao;
import cn.gson.school.entity.caiwu.ShouKuanEntity;
import cn.gson.school.entity.caiwu.ShouKuanInfoEntity;
import cn.gson.school.entity.jiaoxue.StudentEntity;
import cn.gson.school.entity.jiaoxue.TeamStudentEntity;
import cn.gson.school.entity.xitong.DeptEntity;
import cn.gson.school.entity.xitong.ImageEntity;
import cn.gson.school.entity.xitong.RoleEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.entity.zhaosheng.InputStudentEntity;
import cn.gson.school.entity.zhaosheng.SigningrecordEntity;
import cn.gson.school.mappers.zhaosheng.SigningrecordMapper;
import cn.gson.school.service.ImagesService;
/**
 * 签约信息Controller
 */
@Controller
@RequestMapping("/zs-qianyue-list")
public class SigningrecordController {
	
	
	@Autowired
	private SigningrecordMapper signingrecordMapper;

	@Autowired
	private SigninggrecordDao signingrecordDao;
	
	@Autowired
	private InputStudentDao inputStudentDao;
	
	@Autowired
	private UserInfoDao userinfoDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleSerchDao roleSerchDao;
	
	@Autowired
	private StudentDao stuDao;
	
	@Autowired
	private ShouKuanInfoDao skinfoDao;
	
	@Autowired
	private TeamStudentDao teamstuDao;
	
	@Autowired
	private ShouKuanDao skDao;
	
	@Autowired
	private ClassDao classDao;
	
	@Autowired
	private DeptSerchDao deptDao;

	@Autowired
	private ImagesService imgService;
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> index(SigningrecordEntity signinggrecordEntity, HttpServletRequest request,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		System.out.println("签约记录："+signinggrecordEntity);
		HttpSession session = request.getSession();
		UserInfoEntity u = (UserInfoEntity) session.getAttribute("userinfo");
		signinggrecordEntity.setSignId(u.getUserInfoId());
		PageHelper.startPage(pageNum, pageSize);
		List<SigningrecordEntity> pageData = (Page<SigningrecordEntity>) signingrecordMapper.list(signinggrecordEntity);
		PageInfo<SigningrecordEntity> info = new PageInfo<>(pageData);
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	@GetMapping("delete/{id}")
	@ResponseBody
	public JSONObject delete(@PathVariable("id") Long id) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		SigningrecordEntity u;
		if (id != null && (u = signingrecordDao.findOne(id)) != null) {
			signingrecordDao.delete(u);
			obj.put("success", true);
		} else {
			obj.put("message", "此用户不存在！");
		}
		return obj;
	}

	/**
	 * 表单
	 */
	@GetMapping({ "zs-add-qianyue", "zs-add-qianyue/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		DeptEntity dept=deptDao.findOne(3L);
		List<UserInfoEntity> allUserName=userinfoDao.findByDept(dept);
		if (id != null) {
			SigningrecordEntity u = signingrecordDao.findOne(id);
			if (u != null) {
				model.addAttribute("signingrecordEntity", u);
				model.addAttribute("consultant", allUserName);
			}
		}
		model.addAttribute("consultant", allUserName);
		return "zhaosheng/zs-add-qianyue";
	}
	
	/**
	 * 添签约信息
	 */
	@PostMapping("save")
	@ResponseBody
	public Map<String, Object> save(@Valid SigningrecordEntity signingrecordEntity, BindingResult br,HttpServletRequest request,
			@SessionAttribute("user") UserEntity user,
			@RequestParam("file")MultipartFile file) {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		System.out.println("添加签约controller");
		UserEntity userEntity=new UserEntity();
		StudentEntity stu=new StudentEntity();
		ShouKuanEntity sk=new ShouKuanEntity();
		ShouKuanInfoEntity skinfo=new ShouKuanInfoEntity();
		TeamStudentEntity teamstu=new TeamStudentEntity();
		System.out.println("stu:"+stu);
		System.out.println("sk:"+sk);
		if (br.hasErrors()) {
			obj.put("message", "信息校验失败！");
			obj.put("erros", br.getFieldErrors());
			System.out.println("error:"+br.getFieldErrors());
		} else {
			String inputStuName=request.getParameter("inputstuName");
			String userInfoName=request.getParameter("userInfoName");
			String signSchLength=request.getParameter("signSchLength");
			String signTuition=request.getParameter("signTuition");
			String addplus=request.getParameter("addplus");
			UserInfoEntity userinfo=userinfoDao.findByUserName(userInfoName);//找到当前咨询师
			System.out.println("学生姓名："+inputStuName);
			System.out.println("咨询师："+userInfoName);
			System.out.println("学制："+signSchLength);
			System.out.println("学费："+signTuition);
			System.out.println("备注："+addplus);
			if (signingrecordEntity.getSignId() == null) {
				if (inputStuName == null) {
					obj.put("message", "学生姓名不能为空！");
					return obj;
				} else if (userInfoName == null) {
					obj.put("message", "咨询师姓名不能为空！");
					return obj;
				} else if (signTuition == null) {
					obj.put("message", "学费金额数不能为空！");
					return obj;
				} else if (file == null) {
					obj.put("message", "签约凭证不能为空！");
					return obj;
				}
				ImageEntity img = null;
				try {
					img = imgService.upload(user, "sign", file,"");
				} catch (Exception e) {
					obj.put("上传失败！", e);
				}
				InputStudentEntity student=inputStudentDao.findByInputStuName(inputStuName);//找到签约的学生
				System.out.println("签约的学生："+student);
				signingrecordEntity.setInputstuId(student);
				signingrecordEntity.setUserinfoId(userinfo);
				signingrecordEntity.setAddPlus(addplus);
				signingrecordEntity.setImagesId(img);
				signingrecordEntity.setSignSchLength(signSchLength);
				signingrecordEntity.setSignTuition(Integer.parseInt(signTuition));
				signingrecordEntity.setSignTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
				student.setStatus(2);//已签约将学生状态改为已录入
				System.out.println("signingrecordEntity1:"+signingrecordEntity);
				//注册新账号
				userEntity.setRegistTime(new Date());
				userEntity.setUserAccount(student.getInputStuName());
				userEntity.setUserPass(DigestUtils.md5Hex("123456789"));
				userEntity.setImagesId(1L);
				userEntity.setDelete(1);
				userEntity.setEnable(true);
				RoleEntity role= new RoleEntity();
				role=roleSerchDao.findOne(5L);
				List<RoleEntity> roles = new ArrayList<>();
				roles.add(role);
				userEntity.setRoles(roles);

				//添加学生到教学部
				stu.setStudentName(student.getInputStuName());
				stu.setAge(student.getAge());
				Integer sex=null;
				if (student.getGender()==0) {//女
					sex=1;
				}else {//男
					sex=2;
				}
				stu.setGender(sex);
				stu.setDelete(1);
				stu.setAddress(student.getAddress());
				stu.setClassId(1L);
				stu.setQq(student.getQq());
				stu.setState("1");//设置学生状态为已就读
				stu.setOneMoney(Double.parseDouble(signTuition));
				stu.setOneModeTime(new Date());
				stu.setOneOweMoney(0.0);
				stu.setContactNum(student.getPhone());
				stu.setEntranceTime(new Date());
				stu.setOneMoneyMode("刷卡");
				stu.setUserId(userEntity);
				stu.setTotalCredits(0);
				System.out.println("stu1:"+stu);
				userDao.save(userEntity);
				stuDao.save(stu);
				teamstu.setStudentId(stu.getStuId());
				teamstu.setStuidentity("组员");
				teamstu.setTeamId(1L);//为新增学生添加一个默认团队组员身份
				
				//添加收款详情记录
				skinfo.setPayTime(new Date());
				skinfo.setMoney(Double.parseDouble(signTuition));
				skinfo.setUserinfoId(userinfo);
				skinfo.setAddPlus(student.getInputStuName()+"订座费");
				skinfo.setOwedMoney(0.0);
				
				//添加收款记录
				sk.setStudent(stu);
				sk.setClassId(classDao.findOne(1L));
				sk.setShouKuanName("订座费");
				sk.setShouKuanPay("银行卡");
				sk.setShouKuanMoney(Double.parseDouble(signTuition));
				sk.setDiscountMoney(0.0);
				sk.setDiscountReason("无");
				sk.setImagesId(img);
				
				sk.setShoukuaninfoId(skinfo);
				System.out.println("sk1:"+sk);
				
			}else {
				Long inputStuId=Long.parseLong(request.getParameter("inputstuId"));
				InputStudentEntity student=inputStudentDao.findOne(inputStuId);//找到签约的学生
				signingrecordEntity=signingrecordDao.findByInputstuId(student);//找到这条签约记录
				stu=stuDao.findByStudentName(student.getInputStuName());
				userEntity=userDao.findByUserAccount(student.getInputStuName());
				
				ImageEntity img = null;
				try {
					img = imgService.upload(user, "sign", file,"");
				} catch (Exception e) {
					obj.put("上传失败！", e);
				}
				System.out.println("学生姓名1："+inputStuName);
				
				System.out.println("学生姓名2："+student.getInputStuName());
				signingrecordEntity.setInputstuId(student);
				signingrecordEntity.setUserinfoId(userinfo);
				signingrecordEntity.setAddPlus(addplus);
				signingrecordEntity.setImagesId(img);
				signingrecordEntity.setSignSchLength(signSchLength);
				signingrecordEntity.setSignTuition(Integer.parseInt(signTuition));
				student.setStatus(2);//已签约将学生状态改为已录入
				//添加学生到教学部
				stu.setStudentName(student.getInputStuName());
				stu.setAge(student.getAge());
				stu.setGender(student.getGender());
				stu.setDelete(1);
				stu.setAddress(student.getAddress());
				stu.setClassId(1L);
				stu.setQq(student.getQq());
				stu.setState("1");//设置学生状态为已就读
				//添加收款详情记录
				skinfo.setPayTime(new Date());
				skinfo.setMoney(Double.parseDouble(signTuition));
				skinfo.setUserinfoId(userinfo);
				skinfo.setAddPlus(student.getInputStuName()+"订座费");
				//添加收款记录
				sk.setStudent(stu);
				sk.setClassId(classDao.findOne(1L));
				sk.setShouKuanName("订座费");
				sk.setShouKuanPay("银行卡");
				sk.setShouKuanMoney(Double.parseDouble(signTuition));
				sk.setDiscountMoney(0.0);
				sk.setDiscountReason("无");
				sk.setShoukuaninfoId(skinfo);
				/*
				System.out.println("signingrecordEntity:"+signingrecordEntity);
				System.out.println("stu:"+stu);
				System.out.println("sk:"+sk);*/
			}
			teamstuDao.save(teamstu);
			skinfoDao.save(skinfo);
			skDao.save(sk);
			signingrecordDao.save(signingrecordEntity);
			obj.put("success", true);
		}
		return obj;
	}
}
